package com.cre_drt;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SessionManager {

	SharedPreferences pref;
	Editor editor;

	Context context;

	int PRIVATE_MODE = 0; // 0 is private mode
	private static final String PREF_NAME = "drtPref";

	public final String KEY_USERNAME = "username";
	public final String KEY_AUTHORIZATION = "authorization";
	public final String KEY_TIMESTAMP = "timestamp";
	public final String KEY_SESSION_TOKEN_ID = "sessionTokenID";

	@SuppressLint("SimpleDateFormat")
	static SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

	@SuppressLint("CommitPrefEdits")
	public SessionManager(Context context) {
		this.context = context;
		pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}

	public void createLoginSession(String name, String authorization, String sessionTokenID) {

		// Stores the information in the preferences file
		editor.putString(KEY_USERNAME, name);
		editor.putString(KEY_AUTHORIZATION, authorization);
		editor.putString(KEY_TIMESTAMP, df.format(new Date()));
		editor.putString(KEY_SESSION_TOKEN_ID, sessionTokenID);
		editor.commit();
	}

	public HashMap<String, String> getSessionDetails() {
		HashMap<String, String> user = new HashMap<String, String>();

		user.put(KEY_USERNAME, pref.getString(KEY_USERNAME, null));
		user.put(KEY_AUTHORIZATION, pref.getString(KEY_AUTHORIZATION, null));
		user.put(KEY_SESSION_TOKEN_ID, pref.getString(KEY_SESSION_TOKEN_ID, null));
		user.put(KEY_TIMESTAMP, pref.getString(KEY_TIMESTAMP, null));

		return user;
	}

	public void softLogout() {
		editor.clear();
		editor.commit();
	}

	public void hardLogout() {
		// Clear session data
		editor.clear();
		editor.commit();

		// Kill all activities and start login activity
		Intent i = new Intent(context, LogInScreen.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.putExtra("hard logout", true);
		context.startActivity(i);
	}
}
